package com.bigdata.service.impl;

import com.bigdata.dao.SigMapper;
import com.bigdata.entity.pojo.SigStrengthDistribution;
import com.bigdata.entity.pojo.SigTypicalLandMarkStrengthStatistic;
import com.bigdata.entity.pojo.SigTypicalLandMarkStrengthTracking;
import com.bigdata.service.SigService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.math.BigInteger;
import java.util.Arrays;

@Service
public class SigServiceImpl implements SigService {

    @Autowired
    private SigMapper sigMapper;

    @Override
    public Object getSigStrengthDistribution() {
        // 获取原始数据列表
        List<SigStrengthDistribution> distributions = this.sigMapper.selectSigStrengthDistribution();

        // TODO 将原始数据处理为所需格式

        // 创建结果Map
        Map<String, List<Map<String, Object>>> result = new HashMap<>();

        // 按照networkType分组处理数据
        Map<String, List<SigStrengthDistribution>> groupedData = distributions.stream()
                .collect(Collectors.groupingBy(SigStrengthDistribution::getNetworkType));

        // 处理每种网络类型的数据
        groupedData.forEach((networkType, list) -> {
            List<Map<String, Object>> points = list.stream()
                    .map(dist -> {
                        Map<String, Object> point = new HashMap<>();
                        point.put("coord", new Double[]{
                                Double.parseDouble(dist.getUserLon()),
                                Double.parseDouble(dist.getUserLat())
                        });
                        point.put("value", dist.getRssi().intValue());
                        return point;
                    })
                    .collect(Collectors.toList());
            result.put(networkType, points);
        });

        return result;
    }

    @Override
    public Object getSigTypicalLandMarkStrengthTracking() {
        // 获取原始数据列表
        List<SigTypicalLandMarkStrengthTracking> trackings = this.sigMapper.selectSigTypicalLandMarkStrengthTracking();

        //TODO 将原始数据处理为所需格式
        // 创建结果Map
        Map<String, Object> result = new HashMap<>();

        // 1. 获取所有不同的运营商名称作为图例
        List<String> legends = trackings.stream()
                .map(SigTypicalLandMarkStrengthTracking::getNetworkName)
                .distinct()
                .collect(Collectors.toList());

        // 2. 获取所有不同的日期作为x轴数据
        List<String> xAxisData = trackings.stream()
                .map(SigTypicalLandMarkStrengthTracking::getXRate)
                .distinct()
                .sorted()
                .collect(Collectors.toList());

        // 3. 按运营商分组并处理信号强度数据
        Map<String, Map<String, BigInteger>> networkData = trackings.stream()
                .collect(Collectors.groupingBy(
                        SigTypicalLandMarkStrengthTracking::getNetworkName,
                        Collectors.toMap(
                                SigTypicalLandMarkStrengthTracking::getXRate,
                                SigTypicalLandMarkStrengthTracking::getRssi,
                                (v1, v2) -> v1
                        )
                ));

        // 4. 构建seriesData
        List<List<Integer>> seriesData = legends.stream()
                .map(networkName -> {
                    Map<String, BigInteger> networkValues = networkData.get(networkName);
                    return xAxisData.stream()
                            .map(day -> networkValues.getOrDefault(day, BigInteger.ZERO).intValue())
                            .collect(Collectors.toList());
                })
                .collect(Collectors.toList());

        // 5. 组装最终结果
        result.put("legends", legends);
        result.put("xAxisData", xAxisData);
        result.put("seriesData", seriesData);

        return result;
    }

    // 9
    @Override
    public Object getSigTypicalLandMarkStrengthStatistic() {
        // 获取原始数据列表
        List<SigTypicalLandMarkStrengthStatistic> statistics = this.sigMapper
                .selectSigTypicalLandMarkStrengthStatistic();
        // TODO 将原始数据处理为所需格式
        System.out.println(statistics);
        // 初始化图例（legends）和 x 轴数据（xAxisData）
        List<String> legends = Arrays.asList("3G", "2G");
        List<String> xAxisData = Arrays.asList("commercial");

        // 创建一个 Map 来存储各个网络类型在不同地标下的 rssi 强度
        Map<String, Map<String, Integer>> networkStrengthMap = new HashMap<>();
        networkStrengthMap.put("4G", new HashMap<>());
        networkStrengthMap.put("3G", new HashMap<>());
        networkStrengthMap.put("2G", new HashMap<>());

        // 遍历原始数据，将 rssi 按照 networkType 和 landmark 分类
        for (SigTypicalLandMarkStrengthStatistic statistic : statistics) {
            String networkType = statistic.getNetworkType(); // 网络类型：4G, 3G, 2G
            String landmark = statistic.getLandmark(); // 地标：商业区、大学、住宅区
            Integer rssi = statistic.getRssi().intValue(); // 信号强度

            // 存储信号强度数据
            Map<String, Integer> networkData = networkStrengthMap.getOrDefault(networkType, new HashMap<>());
            networkData.put(landmark, rssi);
            networkStrengthMap.put(networkType, networkData);
        }
        System.out.println(networkStrengthMap);

        // 初始化 seriesData
        List<List<Integer>> seriesData = new ArrayList<>();

        // 填充 4G、3G、2G 对应的信号强度数据
        for (String networkType : legends) {
            List<Integer> data = new ArrayList<>();

            // 如果 xAxisData 只有一个项，就直接填充对应信号强度
            if (xAxisData.size() == 1) {
                String landmark = xAxisData.get(0);
                Integer rssi = networkStrengthMap.get(networkType).getOrDefault(landmark, 0); // 默认值为 0
                data.add(rssi);
            } else {
                // 否则按照原来的方式遍历
                for (String landmark : xAxisData.subList(1, xAxisData.size() - 1)) {
                    Integer rssi = networkStrengthMap.get(networkType).getOrDefault(landmark, 0); // 默认值为 0
                    data.add(rssi);
                }
            }

            seriesData.add(data);
        }

        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("legends", legends);
        result.put("xAxisData", xAxisData);
        result.put("seriesData", seriesData);

        return result; // 返回处理后的数据
    }

}
